/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.digitaldiary.notify;

import com.digitaldiary.bean.UserHandler;
import com.digitaldiary.entity.DiaryUser;
import com.digitaldiary.entity.MyPlan;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.transaction.UserTransaction;

/**
 *
 * @author Sanjay
 */
public class MailController extends TimerTask{
   
    private EntityManagerFactory entityManagerFactory= Persistence.createEntityManagerFactory("DigitalDiaryPU");
    @PersistenceContext
    private  EntityManager em;

    
    Mail mail= new Mail();
   
    @Override
    public void run() {
        System.out.println("Mail Controller");
        for(MyPlan p : getMyPlanList()){
            String msg= p.getTitle()+"\n"+p.getDescription()+"\n"+p.getLocation();
            DiaryUser u= getUser(p.getUsername());
            String rMail= u.getEmail();
            mail.sendMail(rMail, "Digital Diary", msg);
        }
        
    }
    
    public List<MyPlan> getMyPlanList(){
     em=entityManagerFactory.createEntityManager();
     try{
         Date date= new Date();
         SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy");
         String curDate= sdf.format(date);
         Query query= em.createQuery("SELECT p FROM MyPlan p WHERE p.alarmDate=:alarmDate");
         query.setParameter("alarmDate", curDate);
         return (List<MyPlan>)query.getResultList();
     }catch(NoResultException e){
     }
     return null;
    }
     
    public DiaryUser getUser(String userName){
        em= entityManagerFactory.createEntityManager();
      try{
          Query q= em.createQuery("SELECT u FROM DiaryUser u WHERE u.userName=:userName");
          q.setParameter("userName", userName);     
          return (DiaryUser)q.getSingleResult();
      }catch(NoResultException e){
       
      }
      return null;
     }
}
